<script setup lang="ts">

import moment from "moment";

const props = defineProps({
  childTabs: {
    type: Array<any>,
    default: [],
  },
  tableName:{
    type: String,
    default: '流量看板',
  }
});
// 结尾处相同字符串去除
const removeSameStr = (arr: string[]) => {
  const newArr = arr;
  for (let i = newArr[0].length; i > 0; i--) {
    const temp = newArr[0].slice(newArr[0].length - i, newArr[0].length);
    const flag = newArr.slice(1).every(item => item.endsWith(temp));
    if (flag) {
      newArr.forEach((item, index) => {
        newArr[index] = item.slice(0, item.length - i);
        if (newArr[index] === '') {
          newArr[index] = '我的';
        } else if (newArr[index] == '昨' || newArr[index] == '今') {
          newArr[index] += '日';
        }
      });
      return newArr;
    }
  }
  return newArr;
}
const dataSource = ref<Array<Object>>([]);
const columns = ref<Array<Object>>([]);
/*
activeTab 数据
{ "dateType": "today", "dateRange": "2023-08-29|2023-08-29", "data": { "yesterday": { "itmUv": [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 0, 0, 1, 1, 0, 3, 1, 1, 1, 1, 2, 0 ] }, "today": { "itmUv": [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 1 ] } }, "indexList": [ { "text": "昨日商品访客数", "value": "yesterday-itmUv", "format": "," }, { "text": "今日商品访客数", "value": "today-itmUv", "format": "," } ], "colorPanel": [ "#2062E6", "#F3D024", "#FF8533", "#4CB5FF", "#BC64E5", "#04C9A8", "#F75CA9", "#00CFCF", "#F85948" ], "fillColorPanel": [ "rgba(32, 98, 230, 0.08)", "rgba(242, 208, 36, 0.2)", "rgba(255, 133, 51, 0.25)", "rgba(76, 188, 255, 0.35)", "rgba(188, 100, 229, 0.35)", "rgba(4, 201, 168, 0.4)", "rgba(247, 92, 196, 0.4)", "rgba(0, 207, 207, 0.3)", "rgba(248, 89, 72, 0.3)" ], "axisTickLineStyle": false, "axisLineStyle": false, "axisTickStyle": { "dy": 4 }, "xAxisOptions": { "interval": "preserveStartEnd" }, "yAxisDomain": [ 0, "auto" ], "xAxisDataKey": "date", "xAxisMinTickGap": 30, "isHideXAxis": false, "legendIconType": "square", "activeDotStyle": { "stroke": "none", "r": 5 }, "hasLegend": true, "hasTooltip": true, "hasCursor": true, "hasLastPoint": false, "hasFirstPoint": true, "hasReferencePoint": false, "referencePointIndexList": [], "hasAnimation": true, "margin": { "top": 0, "left": 0, "right": 0, "bottom": 0 }, "chartOptions": { "stackOffset": "none" }, "graphicalType": "line", "isHideYAxis": false, "stackType": "none", "series": [ { "dataKey": "yesterday-itmUv", "type": "line", "yAxisGroup": "left", "stack": "none", "options": {} }, { "dataKey": "today-itmUv", "type": "line", "yAxisGroup": "left", "stack": "none", "options": {} } ], "yAxis": [ { "type": "left", "hide": false, "domain": [ 0, "auto" ], "options": {}, "tickOptions": {} } ], "tooltipItemSorter": true }
 */
const calcData = () => {
  if (props.childTabs.length === 0) {
    return;
  }
  // 根据childTabs 计算出 dataSource 和 columns
  let _columns: Object[] = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 100,
      fixed: 'left',
      sorter: (a: any, b: any) => {
        return new Date(a.date).getTime() - new Date(b.date).getTime();
      },
    }, {
      title: '类别',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      dataType: 'custom',
      slot: 'type',
      fixed: 'left',
      align: 'center',
      sorter: (a: any, b: any) => {
        return a.type.text.localeCompare(b.type.text);
      }
    }
  ];
  let _dataSource: any[] = [];
  dataSource.value = [];
  props.childTabs.forEach((item, index) => {
    _columns.push({
      title: item.name,
      dataIndex: `${item.key}`,
      key: `${item.key}`,
      width: item.name.length * 20 + 20,
      align: 'center',
      sorter: (a: any, b: any) => {
        return a[item.key] - b[item.key];
      },
    });
  });
  columns.value = _columns;
  let dates: string[] = [];
  const {
    dateRange,
    dateType,
    indexList,
    colorPanel,
    data,
  } = props.childTabs[0].data;
  let _dateRange = dateRange.split('|');
  let _indexes = removeSameStr(indexList.map((item: any) => {
    return item.text;
  }));
  let indexes: Array<Object> = [];
  const getData = (dataField: string, dataKey: string | number, formatString: string) => {
    let data = props.childTabs.map((item1) => {
      try {
        return {
          [item1.key]: format(typeof item1.data.data[dataField][item1.key][dataKey] == 'undefined' ? null : item1.data.data[dataField][item1.key][dataKey], item1.format),
        };
      } catch (e) {
        try {
          return {
            [item1.key]: format(item1.data.data[dataField][dataKey], item1.format),
          };
        } catch (ee) {
          return {
            [item1.key]: null,
          };
        }
      }
    });
    let result: any = {};
    data.forEach((item: any) => {
      for (const itemKey in item) {
        result[itemKey] = item[itemKey];
      }
    })
    return result;
  }
  indexList.forEach((value: Object, index: number) => {
    indexes.push({
      ...value,
      text: _indexes[index],
      color: colorPanel[index],
    })
  })
  // 获取data最长的数组长度
  let maxLength = 0;
  for (let key in data) {
    let fields = indexes[0].value.split('-');
    if (fields.length == 1) {
      if (data[key].length > maxLength) {
        maxLength = data[key].length;
      }
    } else if (fields.length == 2) {
      if (data[key][fields[1]].length > maxLength) {
        maxLength = data[key][fields[1]].length;
      }
    } else if (fields.length == 3) {
      if (data[key][fields[1]][fields[2]].length > maxLength) {
        maxLength = data[key][fields[1]][fields[2]].length;
      }
    }
  }
  // 根据最长的数组长度 生成日期数组
  if (dateType === 'today') {
    // console.log(maxLength);
    // 如果是统计今日数据  xAxis data 为 24小时 HH:mm格式 不足10的前面补0
    for (let i = 0; i < maxLength; i++) {
      dates.push(`${i < 10 ? '0' + i : i}:00`);
    }
  } else {
    let startDate = new Date(_dateRange[0]);
    let endDate = new Date(_dateRange[1]);
    if (startDate.getTime() == endDate.getTime()) {
      for (let i = 0; i < maxLength; i++) {
        dates.push(moment(endDate).format('YYYY-MM-DD'));
        endDate.setDate(endDate.getDate() - 1);
      }
      dates.reverse();
    } else {
      while (startDate <= endDate) {
        dates.push(moment(startDate).format('YYYY-MM-DD'));
        startDate.setDate(startDate.getDate() + 1);
      }
    }
  }
  // 根据dates生成dataSource
  for (let i = 0; i < dates.length; i++) {
    if (dateType === 'today') {
      indexes.map((item: any) => {
        if (item.value.indexOf('yesterday') > -1) {
          _dataSource.push({
            date: moment().subtract(1, 'days').format('YYYY-MM-DD') + ' ' + dates[i],
            type: item,
            ...getData('yesterday', i, item.format),
          })
        } else {
          _dataSource.push({
            date: moment().format('YYYY-MM-DD') + ' ' + dates[i],
            type: item,
            ...getData('today', i, item.format),
          })
        }
      })
    } else {
      indexes.map((item: any) => {
        _dataSource.push({
          date: dates[i],
          type: item,
          ...getData(item.value, i, item.format),
        })
      })
    }
  }
  dataSource.value = _dataSource;
}
const format = (value: any, format: string) => {
  if (value) {
    if (format.indexOf('.2f') > -1) {
      value = value.toFixed(2);
    } else if (format.indexOf('.2%') > -1) {
      value = (value * 100).toFixed(2) + '%';
    }
  }
  return value;
}
calcData();
watch(() => props.childTabs, () => {
  calcData();
}, {deep: true});

// console.log('activeTab 数据', props.childTabs);
</script>

<template>
  <base-table :table-name="tableName" size="small" :columns="columns" :data-source="dataSource" :scroll="{
    y:500
  }"
  >
    <template #type="row">
      <a-tag :color="row.type.color">{{ row.type.text }}</a-tag>
    </template>
  </base-table>
</template>

<style scoped>

</style>
